package common

import (
	"errors"
	"github.com/dgrijalva/jwt-go"
)

type Claims struct {
	Username string `json:"username"`
	Password string `json:"password"`
	jwt.StandardClaims
}

type TokenManager struct {
	TokenKey []byte
	Expire   int64
}

func (that *TokenManager) GenerateToken(username, password string) (string, error) {
	claims := Claims{
		Username: username,
		Password: password,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: that.Expire,
			Issuer:    "token",
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	signedString, err := token.SignedString(that.TokenKey)
	return signedString, err
}

func (that *TokenManager) ValidToken(tokenString string, validFuc func(claims *Claims) error) error {
	token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return that.TokenKey, nil
	})

	if err != nil {
		return err
	}

	if token != nil {
		if claims, ok := token.Claims.(*Claims); ok && token.Valid {
			return validFuc(claims)
		}
	}

	return errors.New("token is invalid")
}
